/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package lu.med.praxiswahl.wahlumed.dao.beans;

import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import lu.med.praxiswahl.wahlumed.dao.beans.daointerface.DoctorsDAOInt;
import lu.med.praxiswahl.wahlumed.model.beans.CustomerTBL;
import lu.med.praxiswahl.wahlumed.model.beans.DoctorsTBL;

/**
 * 
 * @author Patrick kendzo Email: pkendzo@msn.com
 */

@Stateless
public class DoctorsDAO implements DoctorsDAOInt {

	@PersistenceContext(unitName = "gynaekomedic-ejbPU")
	private EntityManager em = null;

	public DoctorsDAO() {
	}

	public void persist(DoctorsTBL todo) {
		em.persist(todo);
		em.flush();
	}

	public void delete(Long id) {
		DoctorsTBL doc = em.find(DoctorsTBL.class, id);

		Object[] customers = doc.getCustomers().toArray();

		for (int i = 0; i < customers.length; i++) {
			CustomerTBL tmpCust = (CustomerTBL) customers[i];
			tmpCust.setHaus_artzID(null);
		}
		em.remove(doc);
		em.flush();
	}

	public void update(DoctorsTBL todo) {
		em.merge(todo);
		em.flush();
	}

	public DoctorsTBL retrieveAddressByID(Long id) {
		return (DoctorsTBL) em.find(DoctorsTBL.class, id);
	}

	@SuppressWarnings("unchecked")
	public List<DoctorsTBL> listAvailableDoctors() {
		try {
			return (List<DoctorsTBL>) em.createQuery(
					"select d from DoctorsTBL d order by nachname")
					.getResultList();
		} catch (Exception e) {
			throw new RuntimeException("DoctorsTBL is empty", e);
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<DoctorsTBL> retrieveAddressEntry(String searchStr) {
		try {
			return (List<DoctorsTBL>) em.createQuery(
					"select d from DoctorsTBL d where d.nachname like '%"
							+ searchStr + "%' or d.vorname like '%" + searchStr
							+ "%' or d.adresse like '%" + searchStr
							+ "%' or d.fachgebiet like '%" + searchStr
							+ "%' or d.ucmCode like '%" + searchStr + "%'")
					.getResultList();
		} catch (Exception e) {
			throw new RuntimeException("Database is empty", e);
		}
	}
}
